import { createRouter, createWebHashHistory } from 'vue-router'

import staticRoutes from '@/router/staticrouter/index'
import {
  dynamicRouter,
  setNavRouterPathList
} from '@/router/dynamicrouter/index'
import store from '@/store'
import { getAsyncRoutes } from '@/api/menu/menu'
import NProgress from 'nprogress' // 进度条

/**
 * @Description : 配置路由
 * @author : August_xiao 1932794922@qq.com
 * @date : 2022-02-27 0:03
 */

const routes = [...staticRoutes, ...dynamicRouter]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savePosition) {
    if (savePosition) {
      //主页刷新保证回到顶部
      if (to.path === '/' && from.path === '/') {
        savePosition.top = 0
      }
      //解决页面从列表页跳转到详情页返回,初始在原来位置
      return savePosition
    } else {
      //解决页面跳转后页面高度和前一个页面高度一样
      return {
        top: 0,
        left: 0
      }
    }
  }
})

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (to.meta.title) {
    document.title = to.meta.title
  }

  if (!store.state.navList.length) {
    getAsyncRoutes()
      .then((res) => {
        store.dispatch('SET_NAV_ROUTE', res.data)
        dynamicRouter.push(...setNavRouterPathList(res.data))
        router.addRoute(...dynamicRouter)
        if (to.path) {
          next({ path: to.path })
        } else {
          NProgress.done()
          next()
        }
      })
      .catch(() => {
        NProgress.done()
        next()
      })
  } else {
    NProgress.done()
    next()
  }
})

export default router
